package com.qf.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

//需要导包-->commons-fileupload
@Component
public class FileUpUtil {

    //参数MultipartFile指获取到的包名

    /**
     * @param request
     * @param uFile
     * @param rootPath 模块的根目录
     * @return
     */
    public static String fileUp(HttpServletRequest request, MultipartFile uFile, String rootPath) {
        try {
            //调用私有的方法,获取文件的上传路径
            File file = getFile(request, uFile, rootPath);
            //文件上传
            uFile.transferTo(file);
            //返回保存到数据库的文件路径
            String s = "http://118.89.242.233/img/" + file.getName();
            System.out.println("返回的路径为:" + s);
            //返回路径
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //出错返回
        return "文件上传失败";
    }

    //文件的上传路径-->单独提取并私有化

    /**
     * @param request
     * @param uFile
     * @param rootPath 模块的根目录（比如user模块存在user文件夹）
     * @return
     */
    private static File getFile(HttpServletRequest request, MultipartFile uFile, String rootPath) {

        String path = "/home/img";
        //获取随机的uuid
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

        //生成一个新的文件名
        String newFileName = uuid + Constant.UNDERLINE_SEPARATOR + uFile.getOriginalFilename();

        //存储文件路径
        String storePath = path + File.separator + newFileName;

        //生成文件夹
        File file = new File(storePath);
        if (!file.exists()) {
            //如果文件夹不存在,则创建文件夹
            file.mkdirs();
        }
        //返回结果
        return file;
    }

    private static String getStorePath(MultipartFile uFile) {
        String originalFilename = uFile.getOriginalFilename();
        int firstLevle = originalFilename.hashCode() & Constant.HASH_CARRY_DIGIT;
        int secondLevle = originalFilename.hashCode() >> 4 & Constant.HASH_CARRY_DIGIT;

        return File.separator + firstLevle + File.separator + secondLevle;
    }

    private static String getSecondaryPath(MultipartFile uFile) {
        String originalFilename = uFile.getOriginalFilename();
        int firstLevle = originalFilename.hashCode() & Constant.HASH_CARRY_DIGIT;
        int secondLevle = originalFilename.hashCode() >> 4 & Constant.HASH_CARRY_DIGIT;

        return Constant.REQUEST_SEPARATOR + firstLevle + Constant.REQUEST_SEPARATOR + secondLevle + Constant.REQUEST_SEPARATOR;
    }
}
